package com.jerry.token;

import com.jerry.common.constant.Constants;
import com.jerry.common.utils.SecurityUtil;
import com.jerry.token.model.TokenModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Filename:    com.jerry.token.TokenManager
 * Description:
 * Copyright:   Copyright (c)2017
 * Company:     lngtop
 *
 * @author: 谢余锋
 * @version: 1.0
 * Create at:   2017/3/6 下午2:22
 * <p/>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2017/3/6      谢余锋        1.0        1.0 Version
 */
@Component
public class TokenManager {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public TokenModel createToken(String userId, String username) {
        String rootToken = UUID.randomUUID().toString().replace("-", "");
        TokenModel tokenModel = new TokenModel(userId, username, rootToken);

        String tokenStr = SecurityUtil.createTokenStr(tokenModel);
        redisTemplate.boundValueOps(userId).set(tokenModel, Constants.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);

        tokenModel.setToken(tokenStr);
        return tokenModel;
    }

    public TokenModel checkToken(String token) {
        TokenModel tokenModel = SecurityUtil.getToken(token);
        if (tokenModel == null) {
            return null;
        }
        TokenModel dbToken = (TokenModel) redisTemplate.boundValueOps(tokenModel.getUserId()).get();
        if (dbToken == null || !dbToken.getToken().equals(tokenModel.getToken())) {
            return null;
        }
        //如果验证成功，说明此用户进行了一次有效操作，延长token的过期时间
        redisTemplate.boundValueOps(tokenModel.getUserId()).expire(Constants.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        return tokenModel;
    }

    public void deleteToken(String token) {
        TokenModel tokenModel = checkToken(token);
        if (tokenModel == null) {
            return;
        }
        redisTemplate.delete(tokenModel.getUserId());
    }
}

